<template>
  <div>
    <el-form ref="chartGridSetting"
             :model="setting"
             label-position="top"
             style="height:auto;">
      <el-tabs v-model="activeName" class="chart-setting">
        <el-tab-pane label="Chart" name="Chart">
          <el-row :gutter="20" type="flex">
            <el-col :span="12" v-for="item in chartsTypeList" :key="item">
              <label :for="item" class="chart-type" :class="{active: setting.chartsType === item}"><i :class="item === 'Bar' ? 'icon_data_bar_fill' : 'icon_data_line_fill'" class="cuifont"></i><span>{{ item }}</span></label>
              <input type="radio" :id="item" name="type" v-model="setting.chartsType" :value="item" style="display: none">
            </el-col>
          </el-row>
          <el-form-item :label="$t(`custom.component.gadget.kpi['${item}']`)" v-for="item in fieldsTypeList" :key="item">
            <el-select v-model="setting[item]"
                       style="width:100%;">
              <el-option v-for="(item,index) in dataSourceColumns"
                         :key="index"
                         :label="item"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <div>
            <el-form-item label="Set Smooth" v-show="setting.chartsType === 'Line'">
              <el-switch v-model="setting.chart.setSmooth"></el-switch>
            </el-form-item>
            <el-form-item label="Show yAxis">
              <el-switch v-model="setting.chart.yAxisShow"></el-switch>
            </el-form-item>
            <el-form-item label="Measure Name">
              <el-input v-model="setting.chart.measure"></el-input>
            </el-form-item>
            <el-form-item label="yAxis Name Location">
              <el-select v-model="setting.chart.yAxisNameLocation" style="width:100%;">
                <el-option label="start" value="start"></el-option>
                <el-option label="center" value="center"></el-option>
                <el-option label="end" value="end"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="yAxis Name Gap">
              <el-input v-model="setting.chart.yAxisNameGap"></el-input>
            </el-form-item>
            <el-form-item label="yAxisValue">
              <el-row :gutter="2">
                <el-col :span="8">
                  <el-input v-model="setting.chart.min" @blur="inputHanlder"></el-input>
                  <span>Min</span>
                </el-col>
                <el-col :span="8">
                  <el-input v-model="setting.chart.max" @blur="inputHanlder"></el-input>
                  <span>Max</span>
                </el-col>
                <el-col :span="8">
                  <el-input v-model="setting.chart.interval" @blur="inputHanlder"></el-input>
                  <span>Interval</span>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="Grid" name="Grid">
          <div class="gridBlock-left" v-show="!showGridColum">
            <div class="icon-right">
              <div class="el-form-item__label">Columns Setting</div>
              <i class="el-icon-arrow-right" @click="showGridColum = true"></i>
            </div>
            <el-form-item label="Show Paging">
              <el-switch v-model="setting.grid.showPaging"></el-switch>
            </el-form-item>
          </div>
          <div class="gridBlock-right" v-show="showGridColum">
            <div class="icon-right">
              <i class="el-icon-back" @click="showGridColum = false"></i>
              <div class="el-form-item__label"><el-switch v-model="expandAllColumn"
                                                          active-text=""
                                                          inactive-text="Expand All"
                                                          @change="expandAll"></el-switch></div>
            </div>
            <draggable handle=".mover"
                       filter=".edititem"
                       v-model="setting.grid.date"
                       chosenClass="chosen"
                       forceFallback="true"
                       animation="1000">
              <transition-group>
                <div class="item_drag"
                     v-for="(item,index) in setting.grid.date"
                     :key="item.field">
                  <el-card class="column-card" shadow="never">
                    <el-row type="flex"
                            class="row-bg mover">
                      <el-col :span="16">
                        <div>
                          <span class="column-field">{{item.field}} </span><i class="column-type">: {{item.type}}</i>
                        </div>
                      </el-col>
                      <el-col :span="8">
                        <div style="float:right">
<!--                          <el-tooltip :open-delay="1000"-->
<!--                                      class="item"-->
<!--                                      effect="dark"-->
<!--                                      :content="item.visible ? 'Display Column ' : 'Hide Column'"-->
<!--                                      placement="bottom-end">-->
<!--                            <el-link style="float: left; border: none;"-->
<!--                                     :underline="false"-->
<!--                                     @click.native="toggleVisible(index, item.visible)"><i v-bind:class="[item.visible ? 'cuifont icon_eye_show': 'cuifont icon_eye_hide','edititem']"-->
<!--                                                                                           style="margin-left: 5px;"></i></el-link>-->
<!--                          </el-tooltip>-->
                          <el-link style="margin-left:5px"
                                   class="column-link edititem"
                                   :underline="false"
                                   @click.native="showSettingClick(index, item.showSetting)"><i v-bind:class="[item.showSetting ? 'el-icon-arrow-up': 'el-icon-arrow-down']"
                                                                                                style="margin-left: 5px;"></i></el-link>
                          <!-- <el-link class="column-link" :underline="false" @click.native="upSortClick(index)" v-show="index != 0"><i class="el-icon-top"></i></el-link>
                          <el-link class="column-link" :underline="false" @click.native="downSortClick(index)" v-show="index != setting.report.columns.length-1"><i class="el-icon-bottom"></i></el-link> -->
                        </div>
                      </el-col>
                    </el-row>
                    <el-form label-position="left"
                             v-show="item.showSetting"
                             label-width="120px"
                             style="border-top: 1px solid #EBEEF5;padding-top: 10px;">
                      <input hidden
                             name="field"
                             v-model="item.field" />
                      <el-form-item label="Header Text">
                        <el-input v-model="item.headerText"></el-input>
                      </el-form-item>
                      <el-form-item label="Header tooltip"
                                    style="margin-bottom: 5px;margin-top: 5px;">
                        <el-input v-model="item.headerTextTooltip"></el-input>
                      </el-form-item>
                      <el-form-item label="Text Align">
                        <el-select v-model="item.textAlign"
                                   placeholder="Please select">
                          <el-option label="Left"
                                     value="Left"></el-option>
                          <el-option label="Center"
                                     value="Center"></el-option>
                          <el-option label="Right"
                                     value="Right"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="Allow Filtering">
                        <el-switch v-model="item.allowFiltering"></el-switch>
                      </el-form-item>
                      <el-form-item label="Disable Html">
                        <el-switch v-model="item.disableHtmlEncode"></el-switch>
                      </el-form-item>
<!--                      <el-tooltip :open-delay="1000"-->
<!--                                  content="Fill in a number to set the column width you need."-->
<!--                                  placement="top-end">-->
<!--                        <el-form-item label="Max Width">-->
<!--                          <el-input v-model="item.maxWidth"-->
<!--                                    placeholder="Please Enter Max Width"></el-input>-->
<!--                        </el-form-item>-->
<!--                      </el-tooltip>-->
                      <!-- <el-form-item label="template">
                            <el-select v-model="item.template" placeholder="Please select" clearable>
                            <el-option v-for="(temItem,temIndex) in columnTemplates" :key="temIndex"  :label="temItem" :value="temItem"></el-option>
                          </el-select>
                          </el-form-item> -->
                      <el-form-item label="Aggregates"
                                    v-if="item.type === 'number'"
                                    style="margin-bottom: 5px;margin-top: 5px;">
                        <el-checkbox-group v-model="item.aggregates"
                                           @change="checkboxChange($event,item)">
                          <el-select multiple
                                     v-model="item.aggregates"
                                     placeholder="Please select"
                                     @change="selectChange($event,item)">
                            <el-option :label="list.label"
                                       :value="list.value"
                                       v-for="list in aggregates"
                                       :key="list.label">
                              <el-checkbox @click.native="(e) => {e.preventDefault()}"
                                           :label="list.label"></el-checkbox>
                            </el-option>
                          </el-select>
                        </el-checkbox-group>
                      </el-form-item>
                      <el-form-item label="Number Format"
                                    v-if="item.type==='number'&&AveragePoint(item.aggregates)"
                                    style="margin-bottom: 5px;margin-top: 5px;">
                        <el-select v-model="item.decimalPoint"
                                   placeholder="Please select">
                          <el-option label="0"
                                     :value="0"></el-option>
                          <el-option label="0.0"
                                     :value="1"></el-option>
                          <el-option label="0.00"
                                     :value="2"></el-option>
                          <el-option label="0.000"
                                     :value="3"></el-option>
                          <el-option label="0.0000"
                                     :value="4"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-form>
                  </el-card>
                </div>
              </transition-group>
            </draggable>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
export default {
  name: 'chartGridSetting',
  components: {
    draggable
  },
  data () {
    return {
      activeName: 'Chart',
      chartsTypeList: ['Bar', 'Line'],
      // fieldsTypeList:['userField','teamField','peerGroupField','dateField','timeFrameField','kpiValueField'],
      fieldsTypeList: ['dateField', 'groupValueField', 'kpiValueField','timeFrameField','userType'],
      expandAllColumn: false,
      showGridColum: false,
      dataSourceColumns: [],
      setting: {
        headerText: '',
        chartsType: 'Line',
        snapshotFrequency: '',
        userType: '',
        groupValueField: '',
        dateField: '',
        timeFrameField: '',
        kpiValueField: '',
        chart: {
          setSmooth: false,
          yAxisShow: true,
          measure: '',
          yAxisNameLocation: 'end',
          yAxisNameGap: '',
          min: '',
          max: '',
          interval: ''
        },
        grid: {
          pageSettings: { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000]},
          showPaging: true,
          columns: [],
          date: [
            {
              "field":"Date",
              "headerText":"Date",
              "headerTextTooltip":null,
              "textAlign":"Left",
              "allowFiltering":true,
              "disableHtmlEncode":false,
              "maxWidth":"auto",
              "showSetting":false,
              "allowEditing":true,
              "allowGrouping":false,
              "showExportOption":false,
              "allowReordering":true,
              "allowSearching":true,
              "allowSorting":true,
              "autoFit":true,
              "enableGroupByFormat":false,
              "foreignKeyField":"Date",
              "showColumnMenu":true,
              "showInColumnChooser":true,
              "sortDirection":"Descending",
              "type":"datetime",
              "template":null,
              "visible":true
            }
          ]
        }
      },
      aggregates: [
        {
          label: 'Sum',
          value: 'Sum'
        },
        {
          label: 'Average',
          value: 'Average'
        },
        {
          label: 'Min',
          value: 'Min'
        },
        {
          label: 'Max',
          value: 'Max'
        },
        {
          label: 'Count',
          value: 'Count'
        }
      ]
    }
  },
  props: [
    'data', 'fieldsList'
  ],
  watch: {
    data (value, oldValue) {
      return this.updateSetting(value)
    },
    'setting.grid.columns': {
      handler: function (val) {
        var res = val.every(item => item.showSetting)
        var result = val.find(item => !item.showSetting)
        if (res) {
          this.expandAllColumn = true
        } else if (result) {
          this.expandAllColumn = false
        }
      },
      deep: true
    },
    fieldsList (val) {
      let temp = []
      this.dataSourceColumns = []
      val.forEach(item => {
        temp.push(item.name)
      })
      this.dataSourceColumns = temp
    }
  },
  computed: {

  },
  created () {
    if (this.data) {
      this.$set(this.data)
    }
    this.expandAllColumn = false
  },
  methods: {
    getData () {
      return this.setting
    },
    updateSetting (value, list, layerStatus) {
      this._.merge(this.setting, value.gadgetSetting)
      this.$emit('update:data', this.setting)
      this.$forceUpdate()
    },
    // setColumns (dataSourceColumns) {
    //   dataSourceColumns.forEach(element => {
    //     if (element.type === 'number' && !element.hasOwnProperty('aggregates')) {
    //       element.aggregates = []
    //     }
    //     if (element.type === 'number' && !element.hasOwnProperty('decimalPoint')) {
    //       this.$set(element, 'decimalPoint', 2)
    //     }
    //   })
    //   this.setting.grid.columns = dataSourceColumns
    //   this.$forceUpdate()
    // },
    // updateSetting (value, list, layerStatus) {
    //   let dataSourceColumns = []
    //   this._.merge(this.setting, value.gadgetSetting)
    //   // value set back
    //   if (value && value.gadgetSetting && value.gadgetSetting.grid &&
    //       value.gadgetSetting.grid.columns && value.gadgetSetting.grid.columns.length > 0 && !layerStatus) {
    //     dataSourceColumns = value.gadgetSetting.grid.columns
    //   } else if (value && list) {
    //     value.gadgetSetting.grid.columns.forEach(iii => {
    //       if (list.some(i => i.name === iii.field)) {
    //         dataSourceColumns.push(iii)
    //       }
    //     })
    //     list.forEach(item => {
    //       const itemObj = {
    //         field: item.name,
    //         headerText: item.name,
    //         textAlign: item.dbType === 'number' ? 'Right' : 'Left',
    //         allowEditing: true,
    //         allowFiltering: true,
    //         allowGrouping: false,
    //         showExportOption: false,
    //         allowReordering: true,
    //         allowSearching: true,
    //         allowSorting: true,
    //         autoFit: true,
    //         disableHtmlEncode: false,
    //         enableGroupByFormat: false,
    //         foreignKeyField: item.name,
    //         showColumnMenu: true,
    //         showInColumnChooser: true,
    //         sortDirection: 'Descending',
    //         type: item.dbType,
    //         template: null,
    //         visible: true,
    //         showSetting: false,
    //         headerTextTooltip: null,
    //         maxWidth: 'auto'
    //       }
    //       if (value.gadgetSetting && value.gadgetSetting.grid && value.gadgetSetting.grid.columns) {
    //         const obj = this._.find(value.gadgetSetting.grid.columns, { field: item.name })
    //         if (!obj) {
    //           dataSourceColumns.push(itemObj)
    //         }
    //       } else {
    //         dataSourceColumns.push(itemObj)
    //       }
    //     })
    //   }
    //   this.setColumns(dataSourceColumns)
    //   this.$emit('update:data', this.setting)
    //   this.$forceUpdate()
    //   return dataSourceColumns
    // },
    toggleVisible (index, visible) {
      this.$set(this.setting.grid.date[index], 'visible', !visible)
      this.$forceUpdate()
    },
    showSettingClick (index, showSetting) {
      this.$set(this.setting.grid.date[index], 'showSetting', !showSetting)
      this.$forceUpdate()
    },
    checkboxChange (e, item) {
      item.aggregates = e
      // this.$set(item, 'aggregates', e)
      this.$forceUpdate()
    },
    selectChange (e, item) {
      item.aggregates = e
      // this.$set(item, 'aggregates', e)
      this.$forceUpdate()
    },
    AveragePoint (aggregates) {
      if (aggregates.includes('Average')) return true
      else return false
    },
    expandAll (val) {
      this.setting.grid.date.filter(item => item.visible).forEach(item => {
        item.showSetting = val
      })
    },
    inputHanlder() {
      if(!this.validate()) {
        return this.$message.error("Invalid input.Minimum value can't exceed maximum value or Interval cannot be less than zero.")
      }
    },
    validate() {
      return (this.setting.chart.interval>0||this.setting.chart.interval==='')&&((Number(this.setting.chart.min) < Number(this.setting.chart.max))||(this.setting.chart.min===''||this.setting.chart.max===''))
    }
  }
}
</script>

<style lang="scss">
.chart-setting {
  .column-card {
    margin-top: 8px;
  }
  .el-card__body {
    padding: 5px 20px !important;
  }
  .column-field {
    font-weight: bold;
  }
  .column-type {
    color: #9ea1a7;
  }
  .column-link {
    float: left;
    border: none;
    margin-left: 3px;
  }
  .el-form-item .el-form-item {
    margin-bottom: 4px;
  }
}
.queryModelDialog #tabsList .chart-setting .is-active{
  background-color: transparent !important;
}
.chart-setting .el-tabs__content {
  overflow: hidden;
}
.chart-setting .el-tabs__nav {
  width: 100%;
}
.chart-setting .el-tabs__item {
  width: 50%;
  text-align: center;
  padding: 0;
  font-weight: bold;
}
.chart-setting .chart-type{
  width: 100%;
  display: flex;
  flex-direction: column;
  border: 2px solid #0000000F;
  border-radius: 4px;
  align-items: center;
  justify-content: center;
  line-height: 1;
  height: 48px;
  color: #0000009B;
  span {
    margin-top: 4px;
  }
}
.chart-setting .active {
  border: 2px solid #17B3A3;
  color: #17B3A3;
}
.chart-setting .icon-right {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 32px;
  i {
    font-size: 18px;
    cursor: pointer;
  }
}
.mover {
  cursor: move;
}
.el-form--label-left .el-form-item__label{
  float: left !important;
}
</style>
